<?php

class MailruService extends Auth
{
    public $clientId='';
    public $clientSecret='';
    protected $token='';
    protected $userInfo=false, $serviceName='mailru';

    public function getUserInfo()
    {
        $info=$this->userInfo;

        return array(
            'user'=>array(
                'login'=>isset($info->uid) ? $info->uid : '',
                'userName'=>isset($info->uid) ? $info->uid : '',
                'password'=>'',
                'confirmCode'=>'',
                'email'=>isset($info->email) ? $info->email : '',
                'isConfirmed'=>1,
                'isActive'=>isset($info->is_verified) ? $info->is_verified : 1,
            ),
            'profile'=>array(
                'firstName'=>isset($info->first_name) ? $info->first_name : '',
                'lastName'=>isset($info->last_name) ? $info->last_name : '',
                'sex'=>$info->sex!=0 ? 1 : 0,
                'img'=>isset($info->has_pic) ? $info->pic : '',
            ),
        );
    }

    public function getToken()
    {
        return $this->token;
    }

    public function getServiceName()
    {
        return $this->serviceName;
    }

    public function firstRequest()
    {
        $redirectUrl='https://connect.mail.ru/oauth/authorize?client_id='.$this->clientId.
            '&response_type=code&redirect_uri='.$this->getReturnUrl();

        Yii::app()->request->redirect($redirectUrl);
    }

    public function secondRequest()
    {
        if($code=Yii::app()->request->getQuery('code')){
            $bodyParams='client_id='.$this->clientId.
                '&client_secret='.$this->clientSecret.
                '&grant_type=authorization_code&code='.$code.
                '&redirect_uri='.$this->getReturnUrl();

            $post=Yii::app()->post->open('https://connect.mail.ru/oauth/token','curl',80);
            $post->body=$bodyParams;
            if($post->sendRequest() && $this->token=$post->result->access_token){
                $sign=md5('app_id='.$this->clientId.'method=users.getInfosecure=1session_key='.$this->token.$this->clientSecret);

                $requestUrl='http://www.appsmail.ru/platform/api?method=users.getInfo&secure=1&app_id='.$this->clientId.
                    '&session_key='.$this->token.
                    '&sig='.$sign;

                if(is_array($request=json_decode(file_get_contents($requestUrl)))){
                    $this->userInfo=$request[0];
                    return true;
                }
            }else{
                $this->quit('Не удалось отправить POST-запрос: '.$post->error);
            }
        }

        return false;
    }
}